<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="分类名称" prop="categoryName">
        <el-input
          v-model="queryParams.categoryName"
          placeholder="请输入分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 192px">
          <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="categoryList"
      row-key="categoryId"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="分类名称" prop="categoryName" :show-overflow-tooltip="true" />
      <el-table-column label="排序" prop="orderNum" width="60" align="center" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button type="text" icon="Plus" @click="handleAdd(scope.row)">新增</el-button>
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级分类">
          <el-tree-select
            v-model="form.parentId"
            :data="categoryOptions"
            :props="{ value: 'categoryId', label: 'categoryName', children: 'children' }"
            value-key="categoryId"
            placeholder="选择上级分类"
          />
        </el-form-item>
        <el-form-item label="分类名称" prop="categoryName">
          <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input-number v-model="form.orderNum" :min="0" :max="999" label="显示顺序" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio v-for="dict in statusOptions" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { listCategory, getCategory, delCategory, addCategory, updateCategory } from '@/api/pet/category'

const { proxy } = getCurrentInstance()

const categoryList = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref('')

// 状态数据字典
const statusOptions = ref([
  { value: '0', label: '正常' },
  { value: '1', label: '停用' }
])

// 分类树选项
const categoryOptions = ref([])

// 查询参数
const queryParams = ref({
  categoryName: '',
  status: ''
})

// 表单参数
const form = ref({
  categoryId: undefined,
  parentId: 0,
  categoryName: '',
  orderNum: 0,
  status: '0',
  remark: ''
})

// 表单校验规则
const rules = ref({
  categoryName: [{ required: true, message: '分类名称不能为空', trigger: 'blur' }],
  orderNum: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }]
})

/** 查询分类列表 */
function getList() {
  loading.value = true
  listCategory(queryParams.value).then(response => {
    const data = response.rows || response.data
    categoryList.value = convertToTree(data)
    loading.value = false
  })
}

/** 查询分类下拉树结构 */
function getTreeselect() {
  listCategory().then(response => {
    const data = response.rows || response.data
    categoryOptions.value = convertToTree(data)
  })
}

/**
 * 将扁平数组转换为树形结构
 * @param {Array} data 扁平数组
 * @returns {Array} 树形结构数组
 */
function convertToTree(data) {
  if (!data || data.length === 0) return []

  // 创建一个映射表用于快速访问节点
  const map = {}
  const result = []

  // 第一步：将所有节点加入映射表，并初始化children数组
  data.forEach(item => {
    map[item.categoryId] = { ...item, children: [] }
  })

  // 第二步：构建树形结构
  data.forEach(item => {
    const node = map[item.categoryId]
    if (item.parentId === 0) {
      // 顶级节点直接加入结果数组
      result.push(node)
    } else {
      // 子节点加入到父节点的children数组
      if (map[item.parentId]) {
        map[item.parentId].children.push(node)
      }
    }
  })

  return result
}

/** 取消按钮 */
function cancel() {
  open.value = false
  reset()
}

/** 表单重置 */
function reset() {
  form.value = {
    categoryId: undefined,
    parentId: 0,
    categoryName: '',
    orderNum: 0,
    status: '0',
    remark: ''
  }
  proxy.$refs['formRef']?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.$refs['queryForm']?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset()
  getTreeselect()
  if (row != null && row.categoryId) {
    form.value.parentId = row.categoryId
  }
  open.value = true
  title.value = '添加分类'
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  getTreeselect()
  getCategory(row.categoryId).then(response => {
    form.value = response.data
    open.value = true
    title.value = '修改分类'
  })
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs['formRef']?.validate(valid => {
    if (valid) {
      if (form.value.categoryId) {
        updateCategory(form.value).then(response => {
          proxy.$modal.msgSuccess('修改成功')
          open.value = false
          getList()
        })
      } else {
        addCategory(form.value).then(response => {
          proxy.$modal.msgSuccess('新增成功')
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.categoryName + '"的数据项？')
    .then(function () {
      return delCategory(row.categoryId)
    })
    .then(() => {
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .catch(() => {})
}

/** 修改状态按钮操作 */
function handleStatusChange(row) {
  let text = row.status === '0' ? '启用' : '停用'
  proxy.$modal
    .confirm('确认要"' + text + '""' + row.categoryName + '"分类吗？')
    .then(function () {
      return updateCategory(row)
    })
    .then(() => {
      proxy.$modal.msgSuccess(text + '成功')
    })
    .catch(function () {
      row.status = row.status === '0' ? '1' : '0'
    })
}

// 页面加载时获取列表数据
onMounted(() => {
  getList()
})
</script>
